import { Bubble, Sender, Welcome, useXAgent, useXChat } from '@ant-design/x';
import { ConfigProvider, Typography } from 'antd';
import { UserOutlined, AliwangwangOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import React from 'react';

import { type GetProp } from 'antd';

const { Paragraph } = Typography;

const roles: GetProp<typeof Bubble.List, 'roles'> = {
	ai: {
		placement: 'start',
		typing: { step: 4, interval: 25 },
		avatar: { icon: <AliwangwangOutlined />, style: { background: '#FFD700' } },
		styles: {
			content: {
				borderRadius: 16,
			},
		},
	},
	local: {
		placement: 'end',
		variant: 'shadow',
		avatar: { icon: <UserOutlined />, style: { background: '#E0282E' } },
	},
};

const App: React.FC = () => {
	// ==================== State ====================

	const [content, setContent] = React.useState('');

	// ==================== Runtime ====================
	const [agent] = useXAgent({
		request: async ({ message }, { onSuccess, onError }) => {
			try {
				const response = await fetch('https://api.coze.cn/v1/workflow/run', {
					method: 'POST',
					headers: {
						Authorization:
							'Bearer pat_sQVwyHjZ30oaarTyE7chfMwnfgx24UN9HshFPI32Ttb2QlibB0KBtbdRDiNUVT97',
						'Content-Type': 'application/json',
					},
					body: JSON.stringify({
						parameters: {
							BOT_USER_INPUT: message,
						},
						workflow_id: '7436444610219573286',
						bot_id: '7437176474702463016',
					}),
				});

				const result = await response.json();
				const parsedData = JSON.parse(result.data);
				const aiResponse = parsedData.data || '抱歉，我没有得到有效回复';

				onSuccess(aiResponse);
			} catch (error) {
				onError(error instanceof Error ? error : new Error('请求失败'));
			}
		},
	});

	const { onRequest, messages } = useXChat({
		agent,
		requestPlaceholder: () => '正在思考中...',
	});

	// ==================== Event ====================
	const onSubmit = (nextContent: string) => {
		if (!nextContent) return;
		onRequest(nextContent);
		setContent('');
	};

	// ==================== Nodes ====================
	const placeholderNode = (
		<Welcome
			style={{
				backgroundImage: 'linear-gradient(97deg, #f2f9fe 0%, #f7f3ff 100%)',
				borderStartStartRadius: 4,
			}}
			icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
			title="你好，我是贾维斯"
			description="我是一个专业的商品咨询助手，可以为您提供商品详情、价格、规格等信息。如果您对任何商品有疑问，都可以随时向我咨询，我会耐心为您解答。让我来帮您找到最适合的商品！"
		/>
	);

	const items: GetProp<typeof Bubble.List, 'items'> = messages.map(({ id, message, status }) => ({
		key: id,
		loading: status === 'loading',
		role: status === 'local' ? 'local' : 'ai',
		content:
			status === 'local' ? (
				message
			) : (
				<Typography>
					<ReactMarkdown
						components={{
							// Markdown 组件的渲染
							p: ({ children }) => (
								<Paragraph
									style={{
										margin: 0,
										whiteSpace: 'pre-wrap',
									}}
								>
									{children}
								</Paragraph>
							),
						}}
					>
						{message}
					</ReactMarkdown>
				</Typography>
			),
	}));

	// ==================== Render ====================
	return (
		<ConfigProvider theme={{ token: { colorPrimary: '#E0282E' } }}>
			<div className="h-screen flex flex-col">
				{/* 头部 */}
				<header className="flex-none h-12 md:h-14 bg-white shadow-sm">
					<h1 className="text-base md:text-lg font-medium text-center leading-[48px] md:leading-[56px]">
						贾维斯助手
					</h1>
				</header>

				{/* 聊天区域 */}
				<main className="flex-1 overflow-hidden">
					<Bubble.List
						className="h-full overflow-y-auto px-3 md:px-6 py-6 md:py-8"
						items={items.length > 0 ? items : [{ content: placeholderNode, variant: 'borderless' }]}
						roles={roles}
					/>
				</main>

				{/* 底部*/}
				<footer className="flex-none bg-white border-t p-3 md:p-4">
					<div className="max-w-xl md:max-w-2xl lg:max-w-4xl mx-auto">
						<Sender
							className="rounded-full shadow-lg"
							value={content}
							onChange={setContent}
							onSubmit={onSubmit}
							loading={agent.isRequesting()}
							placeholder="输入您的问题..."
						/>
					</div>
				</footer>
			</div>
		</ConfigProvider>
	);
};

export default App;
